String.prototype.replaceAll = function (value, targetValue) { //吧f替换成e
    var reg = new RegExp(value, "g"); //创建正则RegExp对象
    return this.replace(reg, targetValue);
}
const SQ_TOOLS_Base64 = require('./base64.js');
const md5 = require('./md5.js');
const Base64 = require('./base64.js');
const sm2Origin = require('../miniprogram_npm/sm-crypto/index').sm2;

import WxmpRsa from "../miniprogram_npm/wxmp-rsa/index"

const createRasEncryptor = function () {
    let ras = new WxmpRsa();
    return ras;
}
const createRasEncryptorUsePublicKey = function (publicKey) {
    if (!this.RsaEcryptorInstance) {
        this.RsaEcryptorInstance = new WxmpRsa();
        if (publicKey && publicKey != '') {
            this.RsaEcryptorInstance.setPublicKey(publicKey)
        }

    }
    return this.RsaEcryptorInstance

}

const createRasDecryptorUsePublicKey = function (privateKey) {
    if (!this.RsaDecryptorInstance) {
        this.RsaDecryptorInstance = new WxmpRsa();
        if (privateKey && privateKey != '') {
            this.RsaDecryptorInstance.setPrivateKey(privateKey)
        }

    }
    return this.RsaDecryptorInstance

}
const sm2 = {
    encrypt: function (data, publicKey) {
        return sm2Origin.doEncrypt(data, publicKey, 0);
    },
    decrypt: function (data, privateKey) {
        return sm2Origin.doDecrypt(data, privateKey, 0);
    },
    generateKeyPairHex: sm2Origin.generateKeyPairHex,
}
// sm2.decrypt("")
let FORMATE_DATE = (second, showSeconds) => {
    // var time
    var date = new Date(parseInt(second));
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var mintuns = date.getMinutes();
    var seconds = date.getSeconds();
    return year + "年" + month + "月" + day + "日  " + (hour > 9 ? hour : '0' + hour) + ":" + (mintuns > 9 ? mintuns : '0' + mintuns) + (showSeconds ? ':' + (seconds > 9 ? seconds : '0' + seconds) : '');
}

let SERIALIZED_BASE64 = function (data) {
    let dataString = JSON.stringify(data);
    let base64String = SQ_TOOLS_Base64.encode(dataString);

    // let newBase64String = base64String.replace(/\+/g, "9144__1-1-1-1-1__4419").replace(/\//g, "5583__1-1-1-1-1__3855").replace(/\=/, "7091__0-0-0-0-0__1907");

    return encodeURIComponent(base64String);
};
let DESERIALIZED_BASE64 = function (dataString) {
    dataString = decodeURIComponent(dataString);
    // let newBase64String = dataString.replace(/9144__1-1-1-1-1__4419/g, "+").replace(/5583__1-1-1-1-1__3855/, "/").replace(/7091__0-0-0-0-0__1907/g, "=");

    let jsonString = SQ_TOOLS_Base64.decode(dataString);
    let data = JSON.parse(jsonString);
    return data;
};
let SQ_TOOLS_ENCODE_URL_PARAM_METHOD = function (object) {
    if (object) {
        return SERIALIZED_BASE64(object);
    }
    return "";
}
let SQ_TOOLS_DECODE_URL_PARAM_METHOD = function (targetString) {
    if (targetString) {
        return DESERIALIZED_BASE64(targetString);
    }
    return {};
}
let SQ_TOOLS_ROUTE_OPEN_PAGE = function (router, path, data) {
    if (data) {
        data = SQ_TOOLS_ENCODE_URL_PARAM_METHOD(data);
        router.push({
            path: path,
            query: {
                data: data
            }
        });
    } else {
        router.push({
            path: path
        });
    }

}
let SQ_TOOLS_ROUTE_GET_DATA = function (route) {
    if (route && route.query && route.query.data) {
        return SQ_TOOLS_DECODE_URL_PARAM_METHOD(route.query.data);
    } else {
        return "";
    }
}
let SQ_TOOLS_ROUTE_OPEN_PAGE_RPLACE = function (router, path, data) {

    if (data) {
        data = SQ_TOOLS_ENCODE_URL_PARAM_METHOD(data);
        router.replace({
            path: path,
            query: {
                data: data
            }
        });
    } else {
        router.replace({
            path: path
        });
    }

}

let SQ_TOOLS_SET_USERINFO_VAlUE = function (data) {
    // SqTools.userinfo = data;
    if (!data || data == '' || data == {} || !data.id || data.id == '') {
        window.localStorage.removeItem("SQ_STORAGE_PNXZPLCLPQXDDEPU_90832_IOPNNIFO");
        return false;
    } else {
        data.logined = true;
        let userinfoString = SQ_TOOLS_ENCODE_URL_PARAM_METHOD(data);
        window.localStorage.setItem("SQ_STORAGE_PNXZPLCLPQXDDEPU_90832_IOPNNIFO", userinfoString);
        SqTools.userinfo = data;
        let vue_instance = new Vue();
        let eventBus = vue_instance.$eventBus;
        eventBus.$postEvent("UserInfoHasChanged");

    }

}

let SQ_TOOLS_RANDOM_STR = function (length) {
    if (!length) {
        length = 13;
    }
    var str = "qwertyuiopasdfghjklzxcvbnm1234567890POIUYTREWQASDFGHJKLMNBVCXZ";
    var strarr = str.split('');
    var targetString = '';
    for (let count = 0; count < length; count++) {
        let rangdomIndex = parseInt(Math.random() * 1000) % 62
        targetString += strarr[rangdomIndex];
    }
    return targetString;
}
let SQ_TOOLS_IS_WECHAT_PLATEFORM = function () {

    var ua = navigator.userAgent.toLowerCase();
    var isWeixin = ua.indexOf('micromessenger') != -1;
    if (isWeixin) {
        return true;
    } else {
        return false;
    }
}
let SQ_TOOLS_GET_USERINFO = function (that) {
    let vue_instance = new Vue();
    let isDebug = vue_instance.$isDebug;


    if (SqTools.globalData.loginHasDisabled) {
        return false;
    }
    if (SqTools.userinfo.logined && SqTools.userinfo.id) {
        return SqTools.userinfo;
    }
    let userInfo_storageString = window.localStorage.getItem("SQ_STORAGE_PNXZPLCLPQXDDEPU_90832_IOPNNIFO");
    if (userInfo_storageString && userInfo_storageString != '') {
        let userinfoParsed = '';
        try {
            userinfoParsed = SQ_TOOLS_DECODE_URL_PARAM_METHOD(userInfo_storageString);
            if (userinfoParsed.logined) {
                REFRESH_USERINFO(userinfoParsed.id);
                SqTools.userinfo = userinfoParsed;
                return userinfoParsed;
            }

        } catch (error) {
            console.error(error);
            GET_USERINFO_FAILED()
        }
    }
    // GET_USERINFO_FAILED()
}
let REFRESH_USERINFO = function (id) {
    let vue_instance = new Vue();
    let refresh = vue_instance.$Urls.user.refresh(id);
    SqTools.get(refresh)
        .then(function (response) {
            var data;
            if (!response.data) {
            } else {
                data = response.data;
                SQ_TOOLS_SET_USERINFO_VAlUE(data);
            }
        })
        .catch(function (error) {
        });
}
let GET_USERINFO_FAILED = function () {

}
let SQ_TOOLS_LOGOUT = function () {
    SQ_TOOLS_SET_USERINFO_VAlUE({});
    let vue_instance = new Vue();
    let fullpath = vue_instance.$Urls.homeHost;

    // window.location.href = fullpath + 'login';

}


//自定义获取图片路径函数
let GET_OBJECT_URL = function (file) {

    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

let CREATE_URL_WITH_PARAM = (url, param) => {
    if (TYPE_IS_OBJ(param)) {
        let keys = Object.keys(param)
        if (keys.length <= 0) {
            return url;
        }
        for (const index in keys) {
            let key = keys[index];
            if (index == 0) {
                if (url.search(/\?/) == -1) {
                    url = url + "?" + key + "=" + param[key];
                } else {
                    url = url + "&" + key + "=" + param[key];
                }
            } else {
                url = url + "&" + key + "=" + param[key];
            }
        }
        return url;
    }
    ;
    return url;
}
let getClassType = (obj) => {
    var type = Object.prototype.toString.call(obj);
    return type.replace("]", '').replace("[", '').replace("object", '').replace(" ", '');
}
let TYPE_IS_OBJ = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type.search("object") != -1 && type.search("Object") != -1) {
        return true;
    }
    return false;
}
let TYPE_IS_ARRAY = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type.search("object") != -1 && type.search("Array") != -1) {
        return true;
    }
    return false;
}
let TYPE_IS_NUMBER = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type.search("object") != -1 && type.search("Number") != -1) {
        return true;
    }
    return false;
}
let TYPE_IS_STRING = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type.search("object") != -1 && type.search("String") != -1) {
        return true;
    }
    return false;
}
let TYPE_IS_DATE = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type.search("object") != -1 && type.search("Date") != -1) {
        return true;
    }
    return false;
}
let TYPE_IS_FUNCTION = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type.search("object") != -1 && type.search("Function") != -1) {
        return true;
    }
    return false;
}

let GET_SQ_STORAGE_KEY = function (key) {

    let SQ_STORAGE_KEY_SPACE = {};
    let SQ_STORAGE_KEY_SPACE_STRING = wx.getStorageSync("SQ_STORAGE_SPACE_DHJCX156QPLV87781_DD_2203");
    if (SQ_STORAGE_KEY_SPACE_STRING && SQ_STORAGE_KEY_SPACE_STRING != '') {
        // SQ_STORAGE_KEY_SPACE = {};
        SQ_STORAGE_KEY_SPACE = DESERIALIZED_BASE64(SQ_STORAGE_KEY_SPACE_STRING);
    }
    let serilized_key = '';
    if (key) {
        serilized_key = SQ_STORAGE_KEY_SPACE[key]
    } else {
        serilized_key = SQ_TOOLS_RANDOM_STR(12) + new Date().getTime();
    }
    if (!serilized_key) {
        serilized_key = SQ_TOOLS_RANDOM_STR(12) + new Date().getTime();
    }
    SQ_STORAGE_KEY_SPACE[key] = serilized_key;
    SQ_STORAGE_KEY_SPACE_STRING = SERIALIZED_BASE64(SQ_STORAGE_KEY_SPACE);
    wx.setStorageSync("SQ_STORAGE_SPACE_DHJCX156QPLV87781_DD_2203", SQ_STORAGE_KEY_SPACE_STRING);
    return serilized_key;
}
let SQ_SET_TOOLS_STORAGE_DATA = function (key, value) {
    if (!key || !value) {
        return false;
    }
    // let SQ_STORAGE_KEY_SPACE = GET_SQ_STORAGE_KEY_SPACE();
    let serilized_key = GET_SQ_STORAGE_KEY(key);
    let valueString = SERIALIZED_BASE64(value);
    wx.setStorageSync(serilized_key, valueString);
}
let SQ_GET_TOOLS_STORAGE_DATA = function (key) {
    let serilized_key = GET_SQ_STORAGE_KEY(key);
    let valueString = wx.getStorageSync(serilized_key);
    if (!valueString) {
        return 0;
    }
    let value = DESERIALIZED_BASE64(valueString);
    return value;
}

var SqTools = {
    sm2: sm2,
    cre: createRasEncryptor,
    createRasEncryptor: createRasEncryptorUsePublicKey,
    createRasDecryptor: createRasDecryptorUsePublicKey,
    md5: md5,
    getClassType: getClassType,
    isObject: TYPE_IS_OBJ,
    isDate: TYPE_IS_DATE,
    isString: TYPE_IS_STRING,
    isNumber: TYPE_IS_NUMBER,
    isFunction: TYPE_IS_FUNCTION,
    isArray: TYPE_IS_ARRAY,
    setsd: SQ_SET_TOOLS_STORAGE_DATA,
    getsd: SQ_GET_TOOLS_STORAGE_DATA,
    base64: SQ_TOOLS_Base64,
    urlParam: {
        encode: SQ_TOOLS_ENCODE_URL_PARAM_METHOD,
        parse: SQ_TOOLS_DECODE_URL_PARAM_METHOD,
    },

    push: SQ_TOOLS_ROUTE_OPEN_PAGE,
    replace: SQ_TOOLS_ROUTE_OPEN_PAGE_RPLACE,
    routeData: SQ_TOOLS_ROUTE_GET_DATA,


    isInWx: SQ_TOOLS_IS_WECHAT_PLATEFORM,
    randomString: SQ_TOOLS_RANDOM_STR,

    getObjectUrl: GET_OBJECT_URL,


    http: (function () {

    })(),
    log(log) {
        let isDev = true;
        if (isDev) {
            console.log("[" + FORMATE_DATE(new Date().getTime(), true) + "] : " + log);
        }

    }
}

module.exports = SqTools;
